package com.wy._02io.fileUtil.ReferTo;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileTypeDetector2 {

    public static String detectFileType(String filePath) throws IOException {
        byte[] buffer = new byte[8];
        try (InputStream is = new FileInputStream(filePath)) {
            is.read(buffer, 0, buffer.length);
        }

        String fileSignature = bytesToHex(buffer);
        System.out.println(fileSignature);
        
        // 定义一些常见的文件类型的魔数
        if (fileSignature.startsWith("FFD8FF")) {
            return "JPEG image";
        } else if (fileSignature.startsWith("89504E47")) {
            return "PNG image";
        } else if (fileSignature.startsWith("47494638")) {
            return "GIF image";
        } else if (fileSignature.startsWith("25504446")) {
            return "PDF document";
        } else if (fileSignature.startsWith("504B0304")) {
            return "ZIP archive";
        } else if (fileSignature.startsWith("1F8B08")) {
            return "GZIP archive";
        }
        // 可以继续添加其他文件类型的魔数

        return "Unknown file type";
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString().toUpperCase();
    }

    public static void main(String[] args) {
        try {
            String filePath = "C:\\Users\\Administrator\\Downloads\\2024.12.9-12.11周货源投放策略(太原).xls"; // 替换为你的文件路径
            String fileType = detectFileType(filePath);
            System.out.println("The file type is: " + fileType);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}